<template>
  <div class="app-container project">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="项目名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入项目名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="负责人" prop="itemChargeName" class="treeselect-form">
        <treeselect
          v-model="queryParams.itemChargeName"
          :options="userOptions"
          :disable-branch-nodes="true"
          :clearable="true"
          value-format="object"
          placeholder="请选择负责人"
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item label="状态" prop="outPlace">
        <el-select v-model="queryParams.status" multiple collapse-tags clearable placeholder="请选择任务状态">
          <el-option
            v-for="item in dict.type.project_status_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['work:project:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          v-hasPermi="['work:project:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          v-hasPermi="['work:project:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />

      <el-table-column label="项目名称" prop="itemName" show-overflow-tooltip min-width="200">
        <template slot-scope="scope">
          <span class="tableProjectName" @click="openProjectDetail(scope.row)">{{ scope.row.itemName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="项目编号" prop="itemNum" show-overflow-tooltip min-width="160" />

      <el-table-column label="负责人" prop="itemChargeName" show-overflow-tooltip min-width="200" />

      <el-table-column label="创建人" prop="creater" min-width="100" />

      <el-table-column label="状态" prop="status" align="center" min-width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.status === '0'" style="color: #e6a23c; font-weight: bold;">{{ typeFormat('project_status_type', scope.row.status) }}</span>
          <span v-if="scope.row.status === '1'" style="color: #409eff; font-weight: bold;">{{ typeFormat('project_status_type', scope.row.status) }}</span>
          <span v-if="scope.row.status === '2'" style="color: #67c23a; font-weight: bold;">{{ typeFormat('project_status_type', scope.row.status) }}</span>
          <span v-if="scope.row.status === '3'" style="color: #f56c6c; font-weight: bold;">{{ typeFormat('project_status_type', scope.row.status) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="开始时间" prop="startTime" min-width="150" />

      <el-table-column label="结束时间" prop="endTime" min-width="150" />

      <el-table-column label="标签" prop="labels" min-width="180" />

      <el-table-column label="备注" prop="remarks" min-width="180">
        <template slot-scope="scope">
          <div class="tableRemarks" v-html="scope.row.remarks" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template v-if="scope.row.roleId !== 1" slot-scope="scope">
          <el-button
            v-if="scope.row.status === '1'"
            v-hasPermi="['work:project:finish']"
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="openEditState(scope.row, '2')"
          >完成</el-button>
          <el-button
            v-if="scope.row.status === '2'"
            v-hasPermi="['work:project:check']"
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="openEditState(scope.row, '3')"
          >验收</el-button>

          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right" />更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-hasPermi="['work:project:query']"
                size="mini"
                type="text"
                icon="el-icon-view"
                command="openProjectDetail"
              >查看</el-dropdown-item>
              <el-dropdown-item
                v-hasPermi="['work:project:edit']"
                size="mini"
                type="text"
                icon="el-icon-edit"
                command="handleUpdate"
              >修改</el-dropdown-item>
              <el-dropdown-item
                v-hasPermi="['work:project:remove']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                command="handleDelete"
              >删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :before-close="cancel" :visible.sync="open" :close-on-click-modal="false" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="标题" prop="itemName">
                  <el-input v-model="form.itemName" type="input" placeholder="请输入标题" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="负责人" prop="itemCharge">
                  <treeselect
                    v-model="form.itemCharge"
                    :disabled="form.status === '2' || form.status === '3'"
                    :options="userOptions"
                    value-consists-of="LEAF_PRIORITY"
                    :multiple="true"
                    :clearable="true"
                    placeholder="请选择项目负责人"
                    @input="outerChanges"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="计划时间" prop="addDateRange">
                  <el-date-picker
                    v-model="addDateRange"
                    :disabled="form.status === '1' || form.status === '2' || form.status === '3'"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="8">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="标签" prop="labels">
                  <el-select v-model="form.labels" multiple clearable placeholder="请选择项目标签">
                    <el-option
                      v-for="item in dict.type.work_type_label"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述" prop="remarks">
              <editor v-model="form.remarks" upload-url="/oa/file/uploadFile" :min-height="192" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 项目详情 -->
    <el-dialog title="项目详情" :visible.sync="projectDetailVisible">
      <el-steps :active="Number(projectDetail.status)" align-center process-status="finish" finish-status="success">
        <el-step title="已创建" :description="projectDetail.creater + '于' + projectDetail.creatime + '创建'" />
        <el-step title="已分配">
          <p v-if="projectDetail.status !== '0'" slot="description">已拆分项目为具体任务并指派负责人员</p>
        </el-step>
        <el-step title="已完成">
          <p v-if="projectDetail.status === '2' || projectDetail.status === '3'" slot="description">
            {{ '操作人：' + stateList[0].creater + '；时间：' + stateList[0].stateTime + '；备注：' + stateList[0].remarks + '；' }}
          </p>
        </el-step>
        <el-step title="已验收">
          <p v-if="projectDetail.status === '3'" slot="description">
            {{ '操作人：' + stateList[1].creater + '；时间：' + stateList[1].stateTime + '；备注：' + stateList[1].remarks + '；' }}
          </p>
        </el-step>
      </el-steps>

      <el-table v-if="projectDetail.status !== '0'" border :data="projectDetailList">
        <el-table-column property="title" label="任务名称" align="center" min-width="200" />
        <el-table-column property="cName" label="负责人" align="center" min-width="150" />
        <el-table-column property="creater" label="创建人" align="center" min-width="150" />

        <el-table-column label="状态" prop="state" align="center" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.state === '0'" style="color: rgb(254, 115, 0); font-weight: bold;">{{ typeFormat('task_status_type', scope.row.state) }}</span>
            <span v-if="scope.row.state === '1'" style="color: rgb(74, 144, 226); font-weight: bold;">{{ typeFormat('task_status_type', scope.row.state) }}</span>
            <span v-if="scope.row.state === '2'" style="color: #82848a; font-weight: bold;">{{ typeFormat('task_status_type', scope.row.state) }}</span>
            <span v-if="scope.row.state === '3'" style="color: #00bd54; font-weight: bold;">{{ typeFormat('task_status_type', scope.row.state) }}</span>
            <span v-if="scope.row.state === '4'" style="color: #ff3030; font-weight: bold;">{{ typeFormat('task_status_type', scope.row.state) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 修改项目状态 -->
    <el-dialog :title="editStateForm.title" :before-close="cancel" :visible.sync="editStateVisible">
      <el-form ref="editStateForm" :model="editStateForm" :rules="editStateRules">
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="editStateForm.remarks" placeholder="请填写意见、建议或总结" type="textarea" autocomplete="off" />
        </el-form-item>
      </el-form>

      <div v-if="projectDetailList.length > 0">
        <svg-icon icon-class="taskGrade1" font-size="15px" />
        <span style="color: #ff4949;">{{ '该项目下尚有' + projectDetailList.length + '个未完成的任务！请先至' }}</span>
        <span style="cursor: pointer; color: #1890ff;" @click="goTaskPage">任务管理</span>
        <span style="color: #ff4949;">页面完成该项目下所有的任务继而完成该项目！</span>
      </div>
      <el-table v-if="projectDetailList.length > 0" border :data="projectDetailList">
        <el-table-column property="title" label="任务名称" align="center" min-width="200" />
        <el-table-column property="cName" label="负责人" align="center" min-width="150" />
        <el-table-column property="creater" label="创建人" align="center" min-width="150" />

        <el-table-column label="状态" prop="state" align="center" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.state === '0'" style="color: rgb(254, 115, 0); font-weight: bold;">{{ typeFormat('task_status_type', scope.row.state) }}</span>
            <span v-if="scope.row.state === '1'" style="color: rgb(74, 144, 226); font-weight: bold;">{{ typeFormat('task_status_type', scope.row.state) }}</span>
            <span v-if="scope.row.state === '2'" style="color: #82848a; font-weight: bold;">{{ typeFormat('task_status_type', scope.row.state) }}</span>
            <span v-if="scope.row.state === '3'" style="color: #00bd54; font-weight: bold;">{{ typeFormat('task_status_type', scope.row.state) }}</span>
            <span v-if="scope.row.state === '4'" style="color: #ff3030; font-weight: bold;">{{ typeFormat('task_status_type', scope.row.state) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" :disabled="projectDetailList.length > 0" @click="editState">确 定</el-button>
      </div>
    </el-dialog>

    <highDelete v-if="showHighDelete" :time="9" :content="deleteWarning" @confirm="confirmDelete" @cancel="showHighDelete = false" />
  </div>
</template>

<script>
import { listItem, userDeptTree, getItemDetail, addItem, updateItem, deleteItem, editProjectState, projectStateList } from '@/api/work/project'
import { listTask } from '@/api/work/task'
import highDelete from '@/components/highDeleteDialog'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'WorkTripSummary',

  components: { Treeselect, highDelete },

  dicts: ['project_status_type', 'work_type_label', 'task_status_type'],

  data() {
    return {
      // 遮罩层
      loading: true,
      // 项目详情dialog
      projectDetailVisible: false,
      // 修改项目状态dialog
      editStateVisible: false,
      // 关联项目
      projectOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      planList: [],
      // 项目详情列表
      projectDetailList: [],
      // 用户树形数据
      userOptions: [],
      // 删除提示
      showHighDelete: false,
      deleteWarning: '',
      roleIds: '',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询日期范围
      dateRange: null,
      // 新增修改日期范围
      addDateRange: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 项目详情
      projectDetail: {},
      // 任务状态列表
      stateList: [],
      // 修改任务状态表单
      editStateForm: {},
      pickerOptions: {
        shortcuts: [{
          text: '3天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }],
        disabledDate(date) {
          return date.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000
        }
      },
      // 表单校验
      rules: {
        itemName: [
          { required: true, message: '请输入项目标题', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        itemCharge: [
          { required: true, message: '请选择负责人', trigger: 'change' }
        ]
      },
      editStateRules: {
        remarks: [
          { required: true, message: '请填写意见、建议或总结', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.getList()
    this.userDeptTree()
  },

  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      const params = {
        ...this.queryParams,
        itemChargeName: this.queryParams.itemChargeName && this.queryParams.itemChargeName.label,
        status: this.queryParams.status && this.queryParams.status.join(',')
      }
      console.log('查询列表参数', params)
      listItem(params).then(response => {
        this.planList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 字典翻译
    typeFormat(type, state) {
      return this.selectDictLabel(this.dict.type[type], state)
    },

    /** 查询部门人员下拉树结构 */
    userDeptTree() {
      userDeptTree().then(response => {
        this.userOptions = this.diGuiTreeEdit(response.data)
      })
    },

    // 禁用最后一级非人员节点
    diGuiTreeEdit(item) {
      const data = item
      const treeAry = []
      for (const i in data) {
        const val = data[i]
        const node = {}
        if (val) {
          if (val.children && val.children.length > 0) {
            node.id = val.id
            node.label = val.label
            node.children = this.diGuiTreeEdit(val.children)
            treeAry.push(node)
          } else {
            if (val.type === '0') {
              node.isDisabled = true
            } else {
              node.isDisabled = false
            }
            node.id = val.id
            node.label = val.label
            treeAry.push(node)
          }
        }
      }
      return treeAry
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.editStateVisible = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        title: undefined,
        cperson: undefined,
        type: undefined,
        labels: undefined,
        remarks: undefined,
        starttime: undefined,
        endtime: undefined
      }
      this.addDateRange = null
      this.resetForm('form')
      this.resetForm('editStateForm')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = null
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection // .map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新建项目'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getItemDetail(row.id).then(response => {
        this.form = {
          ...response.data,
          itemCharge: response.data.itemCharge.split(',').map(Number),
          labels: response.data.labels && response.data.labels.split(',')
        }
        this.addDateRange = [response.data.startTime, response.data.endTime]
        this.open = true
        this.title = '修改项目'
      })
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.title === '修改项目') {
            const params = {
              ...this.form,
              startTime: this.addDateRange && this.addDateRange[0],
              endTime: this.addDateRange && this.addDateRange[1],
              itemCharge: this.form.itemCharge.join(','),
              labels: this.form.labels && this.form.labels.join(',')
            }
            console.log('修改params', params)
            updateItem(params).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.cancel()
              this.getList()
            })
          } else {
            const params = {
              ...this.form,
              status: '0',
              startTime: this.addDateRange && this.addDateRange[0],
              endTime: this.addDateRange && this.addDateRange[1],
              itemCharge: this.form.itemCharge.join(','),
              labels: this.form.labels && this.form.labels.join(',')
            }
            console.log('新增params', params)
            addItem(params).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.cancel()
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.roleIds = row.id || this.ids.map(item => item.id)
      const msg = row.itemName || this.ids.map(item => item.itemName)
      this.deleteWarning = '是否确认删除名称为"' + msg + '"的项目？该操作会把当前项目以及该项目下所有的任务一起删除！！！'
      this.showHighDelete = true
    },

    // 确认删除
    confirmDelete() {
      deleteItem(this.roleIds).then(() => {
        this.showHighDelete = false
        this.getList()
        this.$modal.msgSuccess('删除成功')
      })
    },

    // 新增、修改负责人变动监听
    outerChanges() {
      console.log('新增、修改负责人变动监听')
      this.$refs['form'].validateField('itemCharge')
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/itemPlan/export', {
        ...this.queryParams
      }, `任务列表_${new Date().getTime()}.xlsx`, 'get', 'local')
    },

    // 打开项目详情弹窗
    openProjectDetail(row) {
      getItemDetail(row.id).then(response => {
        this.projectDetail = response.data

        // 获取项目状态列表
        projectStateList({ itemId: row.id }).then(res => {
          console.log('状态列表', res)
          this.stateList = res.rows
        })

        // 查询该项目下任务列表
        if (response.data.status !== '0') {
          listTask({ itemId: response.data.id }).then(res => {
            console.log('任务列表', res)
            this.projectDetailList = res.rows
          })
        }
        this.projectDetailVisible = true
      })
    },

    // 更多操作触发
    handleCommand(command, row) {
      console.log('更多操作触发')
      switch (command) {
        case 'openProjectDetail':
          this.openProjectDetail(row)
          break
        case 'handleUpdate':
          this.handleUpdate(row)
          break
        case 'handleDelete':
          this.handleDelete(row)
          break
        default:
          break
      }
    },

    openEditState(row, state) {
      this.editStateForm = {
        title: state === '2' ? '完成项目' : '验收项目',
        itemId: row.id,
        itemState: state,
        remarks: ''
      }
      this.projectDetailList = []
      if (state === '2') {
        listTask({ itemId: row.id }).then(res => {
          console.log('任务列表', res)
          this.projectDetailList = res.rows.filter(val => {
            return val.state === '0' || val.state === '1'
          })
        })
      }
      this.reset()
      this.editStateVisible = true
    },

    editState() {
      this.$refs['editStateForm'].validate(valid => {
        if (valid) {
          editProjectState(this.editStateForm).then(res => {
            console.log('修改项目状态', res)
            this.$modal.msgSuccess('操作成功！')
            this.editStateVisible = false
            this.getList()
          })
        }
      })
    },

    // 跳转到任务管理页面
    goTaskPage() {
      this.$router.push({ path: 'task' })
    }
  }
}
</script>

<style lang="scss" scoped>
.project{
  .tableRemarks {
    max-width: 100px;
    max-height: 100px;

    ::v-deep p {
      margin: 0;
    }
  }

  .tableProjectName {
    color: #46a6ff;
    cursor: pointer;

    &:hover {
      color: hsl(209, 100%, 50%);
    }
  }
}
.el-date-editor {
  width: 100%;
}
</style>
